import asyncio
import websockets

# 用于控制是否继续推送消息
keep_running = True
aaa = 1
async def handle_connection(websocket):
    global keep_running
    global aaa
    print("Client connected")
    
    try:
        while keep_running:
            # 模拟推送消息
            await websocket.send('1')
            await asyncio.sleep(3)  # 每5秒推送一次消息
    except websockets.ConnectionClosed:
        print("Client disconnected")
    finally:
        print("Connection closed")

async def start_server():
    global keep_running
    keep_running = True
    print("Starting WebSocket server...")
    async with websockets.serve(handle_connection, "localhost", "8765"):
        await asyncio.Future()  # 保持服务器运行

async def stop_server():
    global keep_running
    keep_running = False
    print("Stopping WebSocket server...")

async def main():
    # 启动服务器
    server_task = asyncio.create_task(start_server())
    
    # 模拟手动断开连接
    # await asyncio.sleep(10)  # 30秒后停止服务器
    await stop_server()
    
    # 等待服务器完全停止
    # await asyncio.sleep(5)
    
    # 重新启动服务器
    # print("Restarting WebSocket server...")
    # server_task = asyncio.create_task(start_server())
    
    # 保持主程序运行
    await asyncio.Future()

# 运行主程序
asyncio.run(main())
